# -*- coding: utf-8 -*-

from flask import Blueprint, redirect, render_template,request,flash, url_for
from flask_login import current_user, login_required, login_user, logout_user
from ..models import UserModel
from ..extensions import db

acct_bp = Blueprint(
    'acct_view',
    __name__,
    url_prefix='/',
    template_folder='./templates'
)

@acct_bp.route('/login', methods=['GET','POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if not username or not password:
            flash('Invalid input.')
            return redirect(url_for('acct_view.login'))

        user = UserModel.query.filter_by(email=username).first()
        # 验证用户名和密码是否一致
        if user and user.validate_password(password):
            login_user(user)  # 登入用户
            flash('Login success.')
            return redirect(url_for('movie_view.index'))

        flash('Invalid username or password.')
        return redirect(url_for('acct_view.login'))
    
    return render_template('login.html')


@acct_bp.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
    if request.method == 'POST':
        name = request.form['name']

        if not name or len(name) > 20:
            flash('Invalid input.')
            return redirect(url_for('acct_view.settings'))

        user = UserModel.query.filter_by(id=current_user.id).first()
        user.name = name
        db.session.commit()
        flash('Settings updated.')
        return redirect(url_for('movie_view.index'))

    return render_template('settings.html')


@acct_bp.route('/logout')
@login_required
def logout():
    logout_user()
    flash('Goodbye.')
    return redirect(url_for('movie_view.index'))
